package gob.pgr.xml;

import java.io.StringWriter;
import java.lang.reflect.Field;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.lang.StringUtils;
import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;

public class DomXml {

	public String getXml(List<?> listaObjetos) throws Exception {
		DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
		Document document = documentBuilder.newDocument();
		document.setXmlStandalone(true);
		
		String nombreRaiz = "objeto";
		if (listaObjetos != null && !listaObjetos.isEmpty())
			nombreRaiz = StringUtils.trimToEmpty(StringUtils.lowerCase(listaObjetos.get(0).getClass().getSimpleName()));
		
		Element elementoRaiz = document.createElement(nombreRaiz + "s");
		document.appendChild(elementoRaiz);
		
		Comment comment = document.createComment("Creacion de Archivo XML mediante Java DOM");
		elementoRaiz.appendChild(comment);
		
		String nombreClase = nombreRaiz;
		
		for (Object object : listaObjetos) {
			Element elementoHijo = document.createElement(nombreClase);
			Field[] fields = object.getClass().getDeclaredFields();
			for (Field field : fields) {
				field.setAccessible(true);
				String etiqueta = field.getName();
				Element elemento = document.createElement(etiqueta);
				Text text = document.createTextNode(String.valueOf(field.get(object)));
				elemento.appendChild(text);
				elementoHijo.appendChild(elemento);
			}
			elementoRaiz.appendChild(elementoHijo);
		}
		
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
		transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
		
		StringWriter stringWriter = new StringWriter();
		StreamResult streamResult = new StreamResult(stringWriter);
		DOMSource domSource = new DOMSource(document);
		transformer.transform(domSource, streamResult);
		
		String xml = stringWriter.toString();
		
		return xml;
	}
	
}
